package com.springcloud.zuul.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.springcloud.zuul.common.constant.Constant;
import com.springcloud.zuul.common.constant.ServiceCode;
import com.springcloud.zuul.common.utlis.*;
import com.springcloud.zuul.entity.SysProductEntity;
import com.springcloud.zuul.entity.SysRoleEntity;
import com.springcloud.zuul.exception.ServiceException;
import com.springcloud.zuul.mapper.SysMenuDao;
import com.springcloud.zuul.mapper.SysProductDao;
import com.springcloud.zuul.mapper.SysUserDao;
import com.springcloud.zuul.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @program: springcloud-zuul
 * @description: 产品
 * @author: zhlu
 * @create: 2019-12-31 15:10
 * @Introduction(说明背景故事)
 **/
@Slf4j
@Service("SysProductService")
public class SysProductServiceImpl extends ServiceImpl<SysProductDao, SysProductEntity> implements SysProductService {

    @Autowired
    private SysProductDao sysProductDao;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ComUtils comUtils;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysProductMenuService sysProductMenuService;

    @Autowired
    private SysConfigService sysConfigService;

    /**
     * Description:获取所有产品列表
     * @author zhlu
     * @date 2019/12/31 3:14 下午
     * @param
     * @return com.springcloud.zuul.common.utlis.JsonResult
     */
    @Override
    public IPage getProductList(Map<String,Object>params){

        List<SysProductEntity>productEntityList=this.list();
//        for(SysProductEntity sysProductEntity : productEntityList){
//            SysProductEntity parentProductEntity = sysProductDao.queryByProductId(sysProductEntity.getProductId());
//            if(Objects.nonNull(parentProductEntity)){
//                sysProductEntity.setProductName(parentProductEntity.getProductName());
//            }
//        }

        String keywords= MapUtils.getString(params,"keywords");
        //手动设置超级管理员,拥有最高权限
        List<String> list = Arrays.asList(sysConfigService.getValue("superAdmin").split(","));
        //如果不是超级管理员，则只查询自己创建的角色列表
        if(!list.contains(ContextUtils.getUserId())){
            params.put("userId", ContextUtils.getUserId());
        }
        IPage<SysProductEntity>page=this.page(
                new Query<SysProductEntity>().getPage(params),
                new QueryWrapper<SysProductEntity>()
                        .like(StringUtils.isNotBlank(keywords),"product_name", keywords)
//                        .eq(ContextUtils.getUserId() != null,"user_id", ContextUtils.getUserId())
        );

        return page;
    }

    /**
     * Description:
     * @author zhlu
     * @date 2019/12/31 5:46 下午
     * @param productEntity
     * @return com.springcloud.zuul.common.utlis.JsonResult
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult saveProduct(SysProductEntity productEntity){

        productEntity.setEstate(1);
        //参数效验
        verifyForm(productEntity);

        //如果产品编码不为空，获取是否重编码了
        if (StringUtils.isNotEmpty(productEntity.getProductId())) {
            if (sysProductDao.countProductByProductId(productEntity.getProductId()) > 0) {
                return JsonResult.error(ServiceCode.PRODUCT_EXISTED);
            }
        } else {
            //系统自定义编码
            productEntity.setProductId(comUtils.getLocalTrmSeqNumByLook("product", "security", "sys_product", "product_id"));
        }

        productEntity.setInstm(ConvertDateTime.getCurrentTime());
        productEntity.setInsfnc(this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());
        //保存产品
        super.save(productEntity);

        //产品权限数据去重
        productEntity.setMenuList(Lists.newArrayList(Sets.newHashSet(productEntity.getMenuList())));

        //保存产品与权限功能关联表数据
        sysProductMenuService.saveOrUpdate(productEntity.getProductId(),productEntity.getProductName(),productEntity.getMenuList());

        return JsonResult.success();
    }

    /**
     * Description:表单验证
     * @author zhlu
     * @date 2019/12/31 5:36 下午
     * @param productEntity
     * @return void
     */
    private void verifyForm(SysProductEntity productEntity){

        //产品名称不能为空
        if(StringUtils.isBlank(productEntity.getProductName())){
            throw new ServiceException(ServiceCode.PRODUCT_NAME_NULL);
        }

//        //父级产品编码不能为空
//        if(StringUtils.isBlank(productEntity.getParentId())){
//            throw new ServiceException(ServiceCode.PRODUCT_PARENT_NULL);
//        }
//        //非0的时候去查看是否存在当前产品
//        if(!Constant.DEFAULT_PARENTID.equals(productEntity.getParentId())){
//            //不存在当前产品
//            if(sysProductDao.countProductByProductId(productEntity.getParentId())<=0){
//                throw new ServiceException(ServiceCode.NOT_PRODUCT);
//            }
//        }

        //产品负责人为空
        if(StringUtils.isBlank(productEntity.getUserId())){
            throw new ServiceException(ServiceCode.PRODUCT_USER_NULL);
        }

        //如果不存在当前用户
        if(Objects.isNull(sysUserService.queryByUserId(productEntity.getUserId()))){
            throw new ServiceException(ServiceCode.PRODUCT_USER_EXISTED);
        }

        //产品权限功能不能为空，无意义数据
        if(productEntity.getMenuList().size() == 0){
            throw new ServiceException(ServiceCode.PRODUCT_AUTHORITY);
        }else{
            //获取是否存在这个权限功能编码的数据
            for(String str:productEntity.getMenuList()){
                if(Objects.isNull(sysMenuService.queryByMenuId(str))){
                    throw new ServiceException(ServiceCode.PRODUCT_MENU_EXISTED);
                }
            }
        }
    }

    /**
     * Description:根据产品编码获取产品信息
     * @author zhlu
     * @date 2020/1/6 10:18 上午
     * @param
     * @return com.springcloud.zuul.entity.SysProductEntity
     */
    @Override
    public SysProductEntity queryByProductId(String productId){
        SysProductEntity productEntity=sysProductDao.queryByProductId(productId);
//        if(Objects.nonNull(productEntity)&&!Constant.DEFAULT_PARENTID.equals(productEntity.getParentId())){
//            productEntity.setParentName(sysProductDao.queryByProductId(productEntity.getParentId()).getProductName());
//        }
        //不存在当前产品信息
        if(Objects.isNull(productEntity)){
            throw new ServiceException(ServiceCode.PRODUCT_NULL);
        }
        productEntity.setUserName(sysUserService.queryByUserId(productEntity.getUserId()).getUserName());
        return productEntity;
    }
}
